/* ********************************************************************************
 *      Copyright:  (C) 2025 ZYT
 *                  All rights reserved.
 *
 *       Filename:  sqlite.c
 *    Description:  This file 
 *                        
 *        Version:  1.0.0(07/04/25)
 *         Author:  Zhang yuitng <zhangyuting@163.com>
 *      ChangeLog:  1, Release initial version on "07/04/25 21:28:19"
 *                           
 **********************************************************************************/

#include "sqlite.h"
int sql_init(sqlite3 **db, const char *table_name)
{
	char 			sql_buffer[512] = {0};
	char           *zerrmsg = 0;
	int             rv;

	rv = sqlite3_open("data.db", db);

	if(rv != SQLITE_OK )
	{
		log_error("open database failure: %s.\n", zerrmsg);
		return -1;
	}
	log_info("open database successfully.\n");

	snprintf(sql_buffer, sizeof(sql_buffer),
			"CREATE TABLE IF NOT EXISTS \"%s\" ("
			"HOST    CHAR(20) NOT NULL CHECK(LENGTH(HOST) <= 20), "
			"TIME    DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, "
			"TEMPER  REAL NOT NULL CHECK(TEMPER BETWEEN -50 AND 100)"
			");", 
			table_name);

	rv = sqlite3_exec(*db, sql_buffer, NULL, NULL, &zerrmsg);

	if (rv != SQLITE_OK)
	{
		log_error("create_statement failure: %s.\n", zerrmsg);
		return -1;
	}

	log_info("create statement[%s] successfully.\n", table_name);


	return 0;
}

int sql_insert(sqlite3 *db, packet_t *pack)
{
	char        buffer[128];
	char		*zerrmsg = NULL;

	sprintf(buffer, "INSERT INTO %s VALUES ('%s', '%s', '%s');", pack->dev_sn, pack->dev_sn, pack->dev_time, pack->dev_temp);

	if( sqlite3_exec(db, buffer, 0, 0, &zerrmsg) != SQLITE_OK )
	{
		log_error("insert data to %s failure: %s\n", pack->dev_sn, zerrmsg);
		sqlite3_free(zerrmsg);
		return -1;
	}
	log_info("insert data[%s %s %s]to %s successfully\n", pack->dev_sn, pack->dev_time, pack->dev_temp, pack->dev_sn);

	return 0;
}

int sql_close(sqlite3 **db)
{
	int rv = sqlite3_close(*db);
	if(rv != SQLITE_OK )
	{
		const char *errmsg = sqlite3_errmsg(*db);
		log_error("Failed to close database: %s\n", errmsg);
		return -1;
	}
	*db = NULL; // 关闭成功后置空指针
		log_info("Database closed successfully.\n");
	return 0;
}




